﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.UI;
using System.IO;

namespace Helpers
{
    // This is from the ASP.NET MVC Framework book by Stephen Walther  
    public static class MobileButtonTableHelper
    {
        public static string MobileButtonTable<T>(this HtmlHelper helper)
        {
            return MobileButtonTable<T>(helper, null, null);
        }

        public static string MobileButtonTable<T>(this HtmlHelper helper, object data)
        {
            return MobileButtonTable<T>(helper, data, null);
        }

        public static string MobileButtonTable<T>(this HtmlHelper helper, object data, string[] columns)
        {
            // Get items   
            var items = (IEnumerable<T>)data;
            if (items == null)
                items = (IEnumerable<T>)helper.ViewData.Model;

            // Get column names   
            if (columns == null)
                columns = typeof(T).GetProperties().Select(p => p.Name).ToArray();

            // Create HtmlTextWriter   
            var writer = new HtmlTextWriter(new StringWriter());

            foreach (var item in items)
                RenderRow<T>(helper, writer, columns, item);

            // Return the string   
            return writer.InnerWriter.ToString();
        }

        private static void RenderRow<T>(HtmlHelper helper, HtmlTextWriter writer, string[] columns, T item)
        {
            writer.AddAttribute(HtmlTextWriterAttribute.Type, "button");
            var buttonTitle = typeof(T).GetProperty("StartTime").GetValue(item, null).ToString();
            if (typeof(T).GetProperty("Available").GetValue(item, null).ToString() == "False")
            {
                writer.AddAttribute(HtmlTextWriterAttribute.Class, "CalendarReserved");
                writer.AddAttribute(HtmlTextWriterAttribute.Bgcolor, "#D2EF7C");
                buttonTitle += "\tReserved";
            }
            else
            {
                writer.AddAttribute(HtmlTextWriterAttribute.Class, "CalendarOpen");
                writer.AddAttribute(HtmlTextWriterAttribute.Bgcolor, "White");
                var time = buttonTitle.Substring(0,buttonTitle.IndexOf(':'));
                writer.AddAttribute("onclick", "MobileSubmit(" + time + ")");
                buttonTitle += "\tOpen";
            }
            writer.AddAttribute(HtmlTextWriterAttribute.Value, buttonTitle.ToString());
            //writer.AddAttribute(HtmlTextWriterAttribute.Style, "width: 100px; height: 20px;");
            writer.RenderBeginTag(HtmlTextWriterTag.Input);
            writer.RenderEndTag();
        }
    }
}

